import type { SeriesRow } from '../shared/types.js';
import { ymdAddDays } from '../utils/date.js';

// 基于相邻两点的对数收益插值 close，open/high/low 线性插值并钳制在 min/max 范围
export function interpolateGaps(series: SeriesRow[], maxGapDays = 5): SeriesRow[] {
  if (series.length <= 1) return series;
  const out: SeriesRow[] = [];

  for (let i = 0; i < series.length - 1; i++) {
    const a = series[i];
    const b = series[i + 1];
    out.push(a);
    const gap = daysBetween(a.trade_date, b.trade_date) - 1;
    if (gap <= 0) continue;
    if (gap > maxGapDays) continue; // 不插值超过阈值的缺失

    const steps = gap;
    const logR = Math.log(b.close / a.close);
    const stepR = logR / (steps + 1);
    const openStep = (b.open - a.open) / (steps + 1);
    const highStep = (b.high - a.high) / (steps + 1);
    const lowStep = (b.low - a.low) / (steps + 1);

    for (let k = 1; k <= steps; k++) {
      const trade_date = ymdAddDays(a.trade_date, k);
      const close = a.close * Math.exp(stepR * k);
      // 线性插值，并确保 high >= max(open, close), low <= min(open, close)
      let open = a.open + openStep * k;
      let high = a.high + highStep * k;
      let low = a.low + lowStep * k;
      const maxOC = Math.max(open, close);
      const minOC = Math.min(open, close);
      if (high < maxOC) high = maxOC;
      if (low > minOC) low = minOC;

      out.push({ trade_date, open, high, low, close, vol: undefined });
    }
  }
  out.push(series[series.length - 1]);
  return out;
}

function daysBetween(a: string, b: string): number {
  const ad = new Date(Date.UTC(Number(a.slice(0, 4)), Number(a.slice(4, 6)) - 1, Number(a.slice(6, 8))));
  const bd = new Date(Date.UTC(Number(b.slice(0, 4)), Number(b.slice(4, 6)) - 1, Number(b.slice(6, 8))));
  return Math.round((bd.getTime() - ad.getTime()) / (24 * 3600 * 1000));
}